package com.timanetworks.sensitive.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.timanetworks.sensitive.consts.CncryptionConstant;

/**
 * 比加锁 加密解密工具类
 *
 * @author jizhaojian
 */
public class EncryptionTuils {
    static String encryption_key = CncryptionConstant.encryption_key;
    static String prefix = CncryptionConstant.prefix;
    public static String enDecryptHex(String body) {
        if (ObjectUtil.isEmpty(body)){
            return "";
        }
        //随机生成密钥
        byte[] key = Convert.hexToBytes(encryption_key);
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        if (body.length() > 6 && ObjectUtil.equals(prefix,body.substring(0,6))){
            //解密为字符串
            String bodyStr = body.substring(6,body.length());
            String decryptStr = aes.decryptStr(bodyStr, CharsetUtil.CHARSET_UTF_8);
            return decryptStr;
        }
        //加密为16进制表示
        String encryptHex = aes.encryptHex(body);
        return prefix+encryptHex;
    }

    /**
     * 解密
     * @param body
     * @return
     */
    public static String decrypt(String body) {
        if (ObjectUtil.isEmpty(body)){
            return "";
        }
        //随机生成密钥
        byte[] key = Convert.hexToBytes(encryption_key);
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        if (body.length() > 6 && ObjectUtil.equals(prefix,body.substring(0,6))){
            //解密为字符串
            String bodyStr = body.substring(6,body.length());
            String decryptStr = aes.decryptStr(bodyStr, CharsetUtil.CHARSET_UTF_8);
            return decryptStr;
        }
        return body;
    }
    /**
     * 加密
     * @param body
     * @return
     */
    public static String encrypt(String body) {
        if (ObjectUtil.isEmpty(body)){
            return "";
        }
        //随机生成密钥
        byte[] key = Convert.hexToBytes(encryption_key);
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        if (body.length() > 6 && ObjectUtil.equals(prefix,body.substring(0,6))){
            return body;
        }
        //加密为16进制表示
        String encryptHex = aes.encryptHex(body);
        return prefix+encryptHex;
    }
}
